import React, { useEffect, useState, useReducer } from 'react'
import SubHook from './subHook'
import LoopHook from './loopHook'

function useHooks() {
    const initialState = {
        count: 0,
        total: 0
    }

    const init = (state = initialState) => {
        return {
            ...state
        }
    }

    const reducer = (state, action) => {
        const { count, total } = state

        switch(action.type){
            case "addCount":
                return {
                    ...state,
                    count: count + 5,
                    total: state.total + count + 5
                }
            default:
                return init()
        }
    }

    const [state, dispatch] = useReducer(reducer, initialState, init)

    // 不需要在再次渲染的时候更新total了，直接dispatch时统一更新
    // useEffect(() => {
    //     dispatch({type: "setTotal"})
    // },[])
    
    return (
        <div>
            <div>{state.count}</div>
            <div>{state.total}</div>
            <button onClick={() => dispatch({type: "addCount"})}>更新count</button>

            <SubHook total={state.total} />
            <LoopHook />
        </div>
    )
}
export default useHooks
